package com.wzy.gmail.realtime.util

import com.wzy.gmail.realtime.bean.{DauInfo, PageLog}

import java.lang.reflect.{Field, Method, Modifier}
import scala.util.control.Breaks

/**
 * 实现对象属性拷贝
 */
object MyBeanUtils {

  /**
   * 将srcObj中属性的值拷贝到descObj对应的属性上去。
   */
  def copyProperties(srcObj: AnyRef, descObj: AnyRef): Unit = {
    if (srcObj == null || descObj == null) {
      return
    }
    // 获取目标src中所有属性
    val srcFields: Array[Field] = srcObj.getClass.getDeclaredFields
    // 处理每个属性的拷贝
    for (srcField <- srcFields) {

      Breaks.breakable {
        // get:filedName()
        // set:filedName_$eq(参数类型)
        //getMethodName
        var getMethodName: String = srcField.getName
        //setMethodName
        var setMethodName: String = srcField.getName + "_$eq"
        //从srcObj中获取get方法对象
        val getMethod: Method = srcObj.getClass.getDeclaredMethod(getMethodName)
        //从destObj中获取set方法对象
        val setMethod: Method = {
          try {
            descObj.getClass.getDeclaredMethod(setMethodName, srcField.getType)
          } catch {
            case ex: Exception => Breaks.break()
          }
        }

        // 忽略val属性
        val destField: Field = descObj.getClass.getDeclaredField(srcField.getName)

        if (destField.getModifiers.equals(Modifier.FINAL)) {
          Breaks.break()
        }
        //调用get方法获取到srcObj属性的值，再调用set方法将获取到的属性值赋给destObj属性
        getMethod.invoke(srcObj)
        setMethod.invoke(descObj, getMethod.invoke(srcObj))
      }

    }
  }

  def main(args: Array[String]): Unit = {
    val pageLog: PageLog = PageLog("mid101", "uid101", "prov101", null, null, null, null, null, null, null, null, null, null, null, 123, 123)
    val dauInfo = new DauInfo()
    copyProperties(pageLog,dauInfo)
    println(dauInfo)

  }
}
